<?php

	/**
	* Classe du projet : gbAnalytics
	*
	* @author HAEHNEL Jonathan
	* @date 30/09/2012
	* @copy Application libre open-source sous licence GPL (GNU General Public License)
	*/

	class gbDatabase
	{
		/**
		* Attributs
		*/
		private $dates; // timestamps des enregistrements
		public $corporates; // listes des entreprises
		
		/**
		* Constructeur
		*/
		public function __construct($date)
		{
			$this->dates = array();
			$this->corporates = array();
			
			$this->initDatabase($date);
		}
		
		public function initDatabase($date)
		{
			/*Ouverture du fichier en lecture seule*/
			$filename = TMP_DIRECTORY.'/'.USERNAME.'.txt';
			$file = false;
			if(file_exists($filename))
			{
				$file = fopen($filename,'r');
			}
			
			/* Si le fichier existe deja */
			if ($file)
			{
				$date_init = false;
				while (($buffer = fgets($file)) != false)
				{
					$buffer = str_replace("\n","",$buffer); //suppression des \n
					
					if(!$date_init)
					{
						/* Ajout des anciennes dates */
						/* Formatage: timestamp1:timestamp2:... */
						$tab_date = explode(':',$buffer);
						if($tab_date[0] > 0)
						{
							$this->dates = $tab_date;
							$date_init = true;
						}
					}
					else
					{
						/* Ajout des anciennes donnees */
						/* Formatage: entreprise,init,qty:cours,pv:cours,pv:... */
						 $tab_infos = explode(':',$buffer);
						 $corpo_init = explode(';', $tab_infos[0]);
						 
						 $old_corpo = new gbCorporate($corpo_init[0]);
						 $old_corpo->getQuantity($corpo_init[2]);
						 $old_corpo->getInitialCost($corpo_init[1],$corpo_init[2]);

						 for($i = 1;$i< count($tab_infos); $i++)
						 {
							$current_mesure = explode(';',$tab_infos[$i]);
							$old_corpo->addRecord($current_mesure[0], $current_mesure[1],$corpo_init[2]);
						 }
						 
						 $this->corporates[] = $old_corpo;
					}
				}
				
				/*On ferme le fichier*/
				fclose($file);
			}
		
			/* Ajout de la date courante */
			$this->dates[] = $date;
		}
		
		/**
		* Verifie si une entreprise exite déja dans l'ensemble
		*/
		public function existCorporate($name)
		{
			$found = null;
				for($i = 0; $i < count($this->corporates); $i++)
				{
					if($this->corporates[$i]->getName() == $name)
					{
						$found = $this->corporates[$i];
						break;
					}
				}
			return $found;
		}
		
		/**
		* Fonction mettant a jours la base avec les nouveaux enregistrement
		*/
		public function updateDatabase($name, $cours, $pv, $qty, $init)
		{
			$new_corpo = $this->existCorporate($name);
			if($new_corpo == null)
			{
				$new_corpo = new gbCorporate($name);
				$this->corporates[] = $new_corpo;
			}
			
			$new_corpo->addRecord($cours, $pv, $qty);
			$new_corpo->setInitialCost($init, $qty);
			$new_corpo->setQuantity($qty);
			$new_corpo->update(true);
		}
		
		/**
		* Fonction permettant le nettoyage de la base de donnees avant enregistrement et export
		*/
		public function clean()
		{
			/* Suppression des enregistrements non actifs */
			$enregistrement_suppr = false;
			for($i = 0; $i < count($this->corporates); $i++)
			{
				if($this->corporates[$i]->isUpdated() == false)
				{
					echo ">> Suppression de l'enregistrement : ".$this->corporates[$i]->getName()." \n";
					
					unset($this->corporates[$i]);
					$this->corporates = array_values($this->corporates);
					$enregistrement_suppr = true;
					$i--;
				}
			}
			
			/* Nettoyage de la liste des dates */
			if($enregistrement_suppr == true)
			{
				$max_enregistrement = 0;
				for($i = 0; $i < count($this->corporates); $i++)
				{
					if($this->corporates[$i]->countRecords() > $max_enregistrement)
					{
						$max_enregistrement = $this->corporates[$i]->countRecords();
					}
				}
				
				/* Suppression des dates inutiles */
				for($i = 0; $i < (count($this->dates)-$max_enregistrement); $i++)
				{
					unset($this->dates[$i]);
				}
				$this->dates = array_values($this->dates);
				
				echo ">> Refactorisation OK !\n";
			}
		}
		
		/**
		* Enregistrement de la base de données dans un fichier
		*/
		public function save()
		{
			/* On ouvre le fichier de sauvegarde (automatiquement cree) */
			$filename = TMP_DIRECTORY.'/'.USERNAME.'.txt';
			$file = fopen($filename, 'w+');
			fseek($file,0); // curseur a zero
			
			/* Ecriture des dates */
			$first = true;
			foreach($this->dates as $date)
			{
				if(!$first)
					fputs($file,":");
				else
					$first = false;
					
				fputs($file,$date);
			}
			fputs($file,"\n");
			
			/* Ecriture des enregistrements */
			foreach($this->corporates as $corpo)
			{
				fputs($file,$corpo->getName().";".$corpo->getInitialCost().";".$corpo->getQuantity());
				foreach($corpo->getRecords() as $record)
				{
					fputs($file,":" .$record[0] . ";" . $record[1]);
				}
				fputs($file,"\n");
			}
			/* Fermeture du fichier */
			fclose($file);
			
			echo ">> Sauvegarde OK ! (path:".$filename.") \n";
		}
		
		/**
		* Exportation de la base de données dans un fichiers HTML/JS
		*/
		public function export()
		{
			/* On ouvre le fichier d'export (automatiquement cree si inexistant) */
			$filename = EXPORT_DIRECTORY.'/'.EXPORT_FILENAME;
			$file = fopen($filename, 'w+');
			fseek($file,0); // curseur a zero
			
			/* Pré-traitement (transformations des données en JS) */
			$dates_str = "";
			$corporates_str = "";
			$first = true;
			foreach($this->dates as $date)
			{
				if(!$first)
					$dates_str .= ", ";
				else
					$first = false;
					
				$dates_str .= '\''.date('d/m/Y',$date).'\'';
			}
			
			$first = true;
			foreach($this->corporates as $corpo)
			{
				if(!$first)
					$corporates_str .= ', ';
			
				$corporates_str .= '{ name: \''.substr($corpo->getName(),0,15).'\', data: [' ;
				$first = true;
				
				for($y=0, $i=0; $i < count($this->dates); $i++)
				{
					if(($i+$corpo->countRecords()) < count($this->dates))
					{
						$point_name = "null";
						$point_y = "null";
						$point_label = "null";
						$y++;
					}
					else
					{
						$point_name = date('d M Y',$this->dates[$i]) ." à ".date('H\hi',$this->dates[$i]);
						$records = $corpo->getRecords();
						$point_y = str_replace(',','.',$records[$i-$y][1]);
						$point_label = $records[$i-$y][0] . '€ (init: '.$corpo->getInitialCost().'€)<br/>Quantité: '.$corpo->getQuantity();
					}
					
					if(!$first)
						$corporates_str .= ", ";
					else
						$first = false;
					
					$corporates_str .= '{ name: \''. $point_name.'\', dataLabels: \''.$point_label.'\', y: '.$point_y.' }';
				}
				
				$corporates_str .= ']}';
			}
			
			/* Enregistrement du fichier HTML */
			fputs($file,"<!DOCTYPE html>\n");
			fputs($file,"\t<html>\n");
			fputs($file,"\t\t<head>\n");
			fputs($file,"\t\t\t<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n");
			fputs($file,"\t\t\t<title>Portefeuille de ".USERNAME."</title>\n");
			fputs($file,"\t\t\t<script type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js\"></script>\n");
			
			fputs($file,"\t\t\t<script type=\"text/javascript\">
			$(function () {
				var chart;
				$(document).ready(function() {
					chart = new Highcharts.Chart({
						chart: {
							renderTo: 'container',
							type: 'line',
							marginRight: 150,
							marginBottom: 60
						},
						credits: {
							text: 'Jonathanhaehnel.fr/gb',
							href: 'http://www.jonathanhaehnel.fr/'
						},
						title: {
							text: 'Fluctuations des actions de ".USERNAME."',
							x: -20 //center
						},
						subtitle: {
							text: 'Portefeuille au ".date('d M Y',CURRENT_DATE) ." à ".date('H\hi',CURRENT_DATE) ."',
							x: -20
						},
						plotOptions: {
                            series: {
                                marker: {
                                    radius: 3
                                }
                            }    
                        },
						xAxis: {
						tickInterval: ".UPDATE_PER_DAY.",
                        tickWidth:2,
				 labels: {
					style: {fontSize: '8px'},
					align: 'right',
                    rotation: 90,
					y: +60
                }, 
                categories: [".$dates_str."]
            },
            yAxis: {
                title: {
                    text: 'Plus-value (%)'
                },
                plotLines: [{
                    value: 0,
                    width: 1,
                    color: '#808080'
                }]
            },
            tooltip: {
                formatter: function() {
                        return '<b>'+ this.series.name +'</b><br/><i>'+ this.point.name +'</i>: '+ this.y +'%<br/>Cours: '+ this.point.dataLabels;
                }
            },
            legend: {
                layout: 'vertical',
                align: 'right',
                verticalAlign: 'top',
                x: 0,
                y: 100,
                borderWidth: 1
            },
            series: [".$corporates_str."]
        });
    });
    
});</script>");
			
			
			fputs($file,"\t\t\t<script type=\"text/javascript\" src=\"./js/highcharts.js\"></script>\n");
			fputs($file,"\t\t\t<script type=\"text/javascript\" src=\"./js/modules/exporting.js\"></script>\n");
			fputs($file,"\t\t</head>\n");
			fputs($file,"\t\t<body>\n");
			fputs($file,"\t\t\t<div id=\"container\" style=\"min-width: 400px; height: 400px; margin: 0 auto\"></div>\n");
			fputs($file,"\t\t</body>\n");
			fputs($file,"\t</html>\n");
			
			/* Fermeture du fichier */
			fclose($file);
			
			echo ">> Export OK ! (path:".$filename.") \n";
			echo ">> Terminaison du script ! \n";
		}
		
		/**
		* Fonction permettant d'afficher le contenu de la base (debug use)
		*/
		public function debug()
		{
			echo "\n*****************************\nDEBUG: Affichage de la DB:\n";
			print_r($this->dates);
			echo "\n";
			print_r($this->corporates);
			echo "\n*****************************\n\n";
		}
	
	}


?>
